﻿using System;
using System.IO;
using UnityEngine;

namespace zframe
{
    /// <summary>
    /// 日志级别
    /// </summary>
    public enum ZLoggerLevel { 
        None = 0,   
        All = 1,    
        Log = 2,    
        Warning = 4, 
        Error = 8,  
    }
    public class ZLogger
    {
        private static ZLoggerLevel _loggerLevel = ZLoggerLevel.Log| ZLoggerLevel.Warning; 
        private static string _logFile = string.Empty;
        private static bool _canWrite = true;  
        private static StreamWriter _writer;


        /// <summary>
        /// 设置日志级别;可以通过或运算设置多个等级
        /// </summary>
        /// <param name="level"></param>
        public static void SetLoggerLevel(ZLoggerLevel level)
        {
            _loggerLevel = level;   
        }

        /// <summary>
        /// 设置是否需要写入日志文件
        /// </summary>
        /// <param name="canWrite">true则会写入到 log-日期.txt 文件</param>
        public static void SetCanWrite(bool canWrite)
        {
            _canWrite = canWrite;

        }

        public static void Log(object message)
        {
            if (IsLoggerLevel(ZLoggerLevel.Log))
            {
                Debug.Log(message);
                WriteLog(message.ToString());
            }

        }

        public static void LogFormat(string fmt,params object[] args) {
            
            string msg = string.Format(fmt, args);
            Log(msg);
        }

        public static void Error(object message)
        {
            if (IsLoggerLevel(ZLoggerLevel.Error))
            {
                Debug.LogError(message);
                WriteLog(message.ToString());
            }
        }

        public static void Warning(object message) {
            
            if (IsLoggerLevel(ZLoggerLevel.Warning))
            {
                Debug.LogWarning(message);
                WriteLog(message.ToString());
            }
        }

        private static bool IsLoggerLevel(ZLoggerLevel level)
        {
            return (_loggerLevel & ZLoggerLevel.All) == ZLoggerLevel.All || (_loggerLevel & level) == level;
        }

        private static void WriteLog(string msg) {
            if (!_canWrite)
            {
                return;
            }
            if (_writer == null)
            {
                string fileName = GetLogFileName();
                _writer = File.AppendText(fileName);
                _writer.AutoFlush = true;   
            }
            _writer.WriteLine(msg);
            _writer.Close();
            _writer = null; 
        }

        private static string GetLogFileName()
        {
            if (string.IsNullOrEmpty(_logFile)) {
                DateTime dt = DateTime.Now;
                _logFile = Path.Combine(Application.persistentDataPath, "log-"+dt.ToString("yyyy-MM-dd")+".txt");
                
            }
            return _logFile;
        }
    }
}
